package com.mine.frame.mylandemo.ui.autorail

import android.annotation.SuppressLint
import android.app.Service
import android.content.ComponentName
import android.content.ServiceConnection
import android.os.Bundle
import android.os.IBinder
import android.text.Editable
import android.view.View
import com.blankj.utilcode.util.ClickUtils
import com.blankj.utilcode.util.KeyboardUtils
import com.blankj.utilcode.util.ServiceUtils
import com.blankj.utilcode.util.SnackbarUtils
import com.mine.frame.common.base.BaseActivity
import com.mine.frame.mylandemo.R
import com.mine.frame.mylandemo.adapter.forick.Panel3In1Adapter
import com.mine.frame.mylandemo.entity.forick.ControlBean
import com.mine.frame.mylandemo.mvp.iview.IDreamCurtain
import com.mine.frame.mylandemo.mvp.presenter.DreamCurtainPresenter
import com.swallowsonny.convertextlibrary.hex2ByteArray
import com.swallowsonny.convertextlibrary.toHexString
import com.third.device.mg.serialport.listener.MGNettyConnectListener
import com.third.device.mg.serialport.service.MGSocketService
import com.third.device.mg.serialport.utils.checkHexString
import com.third.device.mg.serialport.utils.hexToBytes
import kotlinx.android.synthetic.main.atv_forick_panel_3in1.*
import kotlinx.android.synthetic.main.layout_connect.*

/**
 * @Date 2022/2/12
 * Description:
 * 波特率：9600
 */
@SuppressLint("SetTextI18n")
class DreamCurtainAtv : BaseActivity<IDreamCurtain, DreamCurtainPresenter>(), IDreamCurtain,
    MGNettyConnectListener {
    /*当前连接的IP地址 和 端口号*/
    private var ipStr = ""
    private var port = 61233

    private val mAdapter by lazy { Panel3In1Adapter() }
    override fun initLayoutId(): Int = R.layout.atv_forick_panel_3in1

    override fun initPresenter(): DreamCurtainPresenter = DreamCurtainPresenter(this)

    private val serviceConnect: ServiceConnection by lazy {
        object : ServiceConnection {
            override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
                SnackbarUtils.with(tvInfo).setMessage("正在连接服务器...").showSuccess()
                MGSocketService.get().setListener(this@DreamCurtainAtv)
            }

            override fun onServiceDisconnected(name: ComponentName?) {
            }
        }
    }

    override fun initLayoutAfter(savedInstanceState: Bundle?) {
        ipStr = intent?.getStringExtra("sel-ip").toString()
        edtIP.text = Editable.Factory.getInstance().newEditable(ipStr)
        connectAndDisconnect()
        initRecycler()
        refreshDefaultID()
        mPresenter.createControlData()
    }

    /**
     * 连接和取消连接
     */
    private fun connectAndDisconnect() {
        ClickUtils.applySingleDebouncing(arrayOf(btnConnect, btnDisconnect)) {
            when (it.id) {
                R.id.btnConnect -> {
                    KeyboardUtils.hideSoftInput(this)
                    if (edtIP.text.isNullOrEmpty()) {
                        SnackbarUtils.with(edtIP).setMessage("请输入IP地址").showWarning()
                        return@applySingleDebouncing
                    } else {
                        ipStr = edtIP.text.toString()
                    }


                    if (edtPort.text.isNullOrEmpty()) {
                        SnackbarUtils.with(edtIP).setMessage("请输入端口号").showWarning()
                        return@applySingleDebouncing
                    } else {
                        port = edtPort.text.toString().toInt()
                        if (port < 1 || port > 65535) {
                            SnackbarUtils.with(edtIP).setMessage("端口号异常(1,65535)").showWarning()
                            return@applySingleDebouncing
                        }
                    }
                    if (ipStr.isEmpty()) {
                        SnackbarUtils.with(edtIP).setMessage("IP地址异常").showError()
                        return@applySingleDebouncing
                    }

                    initSocket()
                }
                R.id.btnDisconnect -> {
                    MGSocketService.get().disconnect(ipStr, port)
                }
            }
        }

    }


    override fun onStart() {
        super.onStart()
        if (!MGSocketService.get().isBind) {
            ServiceUtils.bindService(
                MGSocketService::class.java,
                serviceConnect,
                Service.BIND_AUTO_CREATE
            )
        }
    }


    /**
     * 创建Socket连接
     */
    private fun initSocket() {
        MGSocketService.get().connectNetty(ipStr, port)
    }


    /**
     * 更新指示器
     */
    private fun updateIndicator(connect: Boolean) {
        val resId = if (connect) {
            R.drawable.blue_circle
        } else {
            R.drawable.red_circle
        }
        viewIndicator.setBackgroundResource(resId)
    }

    override fun onDestroy() {
        super.onDestroy()
        if (MGSocketService.get().isBind) {
            ServiceUtils.unbindService(serviceConnect)
        }
    }

    private fun initRecycler() {
        mRecycler.adapter = mAdapter
        mAdapter.setOnItemClickListener { _, _, position ->
            val controlBean = mAdapter.data[position]
            if (!controlBean.isHeader) {
                controlBean.command?.let {
                    MGSocketService.get().write(ipStr, port, it)
                } ?: let {
                    SnackbarUtils.with(btnConnect).setMessage("指令未空").showWarning(true)
                }
            }
        }
    }


    /**
     * 刷新默认ID
     */
    private fun refreshDefaultID() {
        tvTitle.visibility = View.VISIBLE
        edtId.visibility = View.VISIBLE
        btnCreate.visibility = View.VISIBLE
        ClickUtils.applySingleDebouncing(btnCreate) {
            edtId.text?.let {
                val str = it.toString().trim()
                if (str.checkHexString() && str.length == 4) {
                    mPresenter.testId = str.hexToBytes()
                    mPresenter.createControlData()
                    KeyboardUtils.hideSoftInput(edtId)
                    SnackbarUtils.with(btnCreate).setMessage("指令更新成功").showSuccess(true)
                } else {
                    SnackbarUtils.with(btnCreate).setMessage("请输入有效ID").showWarning(true)
                }
            } ?: SnackbarUtils.with(btnCreate).setMessage("请输入有效ID").showWarning(true)
        }
    }

    override fun connectBack(ip: String, port: Int) {
        updateIndicator(true)
    }

    override fun disconnectBack(ip: String, port: Int) {
        updateIndicator(false)
    }


    override fun readBack(ip: String, port: Int, result: ByteArray) {
        SnackbarUtils.with(btnConnect).setMessage("收到消息").showSuccess(true)
        tvInfo.text = "接收:${result.toHexString(true)}"
    }

    override fun writeBack(ip: String, port: Int, successful: Boolean, data: ByteArray) {
        if (successful) {
            SnackbarUtils.with(btnConnect).setMessage("发送成功").showSuccess(true)
        } else {
            SnackbarUtils.with(btnConnect).setMessage("发送失败").showError(true)
        }
    }

    override fun errorBack(ip: String, port: Int, error: Throwable) {
        error.message?.let {
            showErr(it)
        }
    }

    override fun initControlList(data: MutableList<ControlBean>) {
        mAdapter.setList(data)
    }
}